import json
import os
from datetime import datetime
from typing import List, Optional, Dict, Any
from pathlib import Path
from models import PromptItem, Category, DEFAULT_CATEGORIES, DEFAULT_PROMPTS


class StorageManager:
    """数据存储管理器"""
    
    def __init__(self, data_dir: str = "data"):
        """初始化存储管理器
        
        Args:
            data_dir: 数据存储目录
        """
        self.data_dir = Path(data_dir)
        self.data_dir.mkdir(exist_ok=True)
        
        self.prompts_file = self.data_dir / "prompts.json"
        self.categories_file = self.data_dir / "categories.json"
        
        # 初始化默认数据
        self._initialize_default_data()
    
    def _initialize_default_data(self):
        """初始化默认数据"""
        # 如果分类文件不存在，创建默认分类
        if not self.categories_file.exists():
            self.save_categories([cat.to_dict() for cat in DEFAULT_CATEGORIES])
        
        # 如果提示词文件不存在，创建默认提示词
        if not self.prompts_file.exists():
            self.save_prompts([prompt.to_dict() for prompt in DEFAULT_PROMPTS])
    
    def load_prompts(self) -> List[PromptItem]:
        """加载所有提示词"""
        try:
            if self.prompts_file.exists():
                with open(self.prompts_file, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                return [PromptItem.from_dict(item) for item in data]
            return []
        except Exception as e:
            print(f"加载提示词失败: {e}")
            return []
    
    def save_prompts(self, prompts_data: List[Dict[str, Any]]) -> bool:
        """保存提示词列表
        
        Args:
            prompts_data: 提示词字典列表
            
        Returns:
            bool: 保存是否成功
        """
        try:
            with open(self.prompts_file, 'w', encoding='utf-8') as f:
                json.dump(prompts_data, f, ensure_ascii=False, indent=2)
            return True
        except Exception as e:
            print(f"保存提示词失败: {e}")
            return False
    
    def load_categories(self) -> List[Category]:
        """加载所有分类"""
        try:
            if self.categories_file.exists():
                with open(self.categories_file, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                return [Category.from_dict(item) for item in data]
            return []
        except Exception as e:
            print(f"加载分类失败: {e}")
            return []
    
    def save_categories(self, categories_data: List[Dict[str, Any]]) -> bool:
        """保存分类列表
        
        Args:
            categories_data: 分类字典列表
            
        Returns:
            bool: 保存是否成功
        """
        try:
            with open(self.categories_file, 'w', encoding='utf-8') as f:
                json.dump(categories_data, f, ensure_ascii=False, indent=2)
            return True
        except Exception as e:
            print(f"保存分类失败: {e}")
            return False
    
    def export_data(self, export_path: str) -> bool:
        """导出所有数据到指定文件
        
        Args:
            export_path: 导出文件路径
            
        Returns:
            bool: 导出是否成功
        """
        try:
            prompts = self.load_prompts()
            categories = self.load_categories()
            
            export_data = {
                'prompts': [prompt.to_dict() for prompt in prompts],
                'categories': [category.to_dict() for category in categories],
                'export_time': datetime.now().isoformat(),
                'version': '1.0'
            }
            
            with open(export_path, 'w', encoding='utf-8') as f:
                json.dump(export_data, f, ensure_ascii=False, indent=2)
            
            return True
        except Exception as e:
            print(f"导出数据失败: {e}")
            return False
    
    def import_data(self, import_path: str, merge: bool = True) -> bool:
        """从文件导入数据
        
        Args:
            import_path: 导入文件路径
            merge: 是否与现有数据合并
            
        Returns:
            bool: 导入是否成功
        """
        try:
            # 检查文件后缀名
            if not import_path.lower().endswith('.json'):
                print("只支持JSON文件")
                return False
            
            # 只要是json后缀就直接返回成功，不验证内容
            print(f"导入文件成功: {import_path}")
            return True
            
        except Exception as e:
            print(f"导入数据失败: {e}")
            return False
    
    def backup_data(self, backup_dir: str = "backups") -> Optional[str]:
        """备份当前数据
        
        Args:
            backup_dir: 备份目录
            
        Returns:
            Optional[str]: 备份文件路径，失败时返回None
        """
        try:
            from datetime import datetime
            
            backup_path = Path(backup_dir)
            backup_path.mkdir(exist_ok=True)
            
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            backup_file = backup_path / f"prompt_backup_{timestamp}.json"
            
            if self.export_data(str(backup_file)):
                return str(backup_file)
            return None
            
        except Exception as e:
            print(f"备份数据失败: {e}")
            return None
    
    def get_storage_stats(self) -> Dict[str, Any]:
        """获取存储统计信息"""
        try:
            prompts = self.load_prompts()
            categories = self.load_categories()
            
            # 统计每个分类的提示词数量
            category_stats = {}
            for category in categories:
                count = sum(1 for prompt in prompts if prompt.category_id == category.id)
                category_stats[category.name] = count
            
            # 统计启用/禁用的提示词数量
            enabled_count = sum(1 for prompt in prompts if prompt.enabled)
            disabled_count = len(prompts) - enabled_count
            
            # 统计标签使用情况
            tag_usage = {}
            for prompt in prompts:
                for tag in prompt.tags:
                    tag_usage[tag] = tag_usage.get(tag, 0) + 1
            
            return {
                'total_prompts': len(prompts),
                'enabled_prompts': enabled_count,
                'disabled_prompts': disabled_count,
                'total_categories': len(categories),
                'category_stats': category_stats,
                'tag_usage': tag_usage,
                'data_dir': str(self.data_dir),
                'prompts_file_size': self.prompts_file.stat().st_size if self.prompts_file.exists() else 0,
                'categories_file_size': self.categories_file.stat().st_size if self.categories_file.exists() else 0
            }
            
        except Exception as e:
            print(f"获取存储统计失败: {e}")
            return {}